<template>
	<!-- 面包屑导航区域 -->
	<div class="user_content">
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/home' }"> 首页</el-breadcrumb-item>
			<el-breadcrumb-item>用户管理</el-breadcrumb-item>
			<el-breadcrumb-item>用户列表</el-breadcrumb-item>
		</el-breadcrumb>

		<!-- 卡片视图区域 -->
		<el-card>
			<el-row :gutter="20">
				<el-col :span="8">
					<!--搜索框-->
					<el-input v-model="queryInfo.query" clearable placeholder="请输入内容" @clear="getUserList">
						<!--搜索按钮-->
						<el-button slot="append" icon="el-icon-search" @click="getUserList"> 搜索 </el-button>
					</el-input>
				</el-col>
				<el-col :span="4">
					<el-button type="primary" @click="dialogVisible = true"> 添加用户 </el-button>
				</el-col>
			</el-row>
			<!--用户列表区域-->
			<el-table :data="userList" border stripe>
				<el-table-column type="index" />
				<el-table-column label="姓名" prop="username" />
				<el-table-column label="邮箱" prop="email" />
				<el-table-column label="电话" prop="mobile" />
				<el-table-column label="角色" prop="role_name" />
				<el-table-column label="状态">
					<!--作用域插槽 开关-->
					<template slot-scope="scope">
						<el-switch v-model="scope.row.mg_state" @change="useStatuChange(scope.row)" />
					</template>
				</el-table-column>
				<el-table-column label="操作" width="180">
					<!--作用域插槽 操作-->
					<template slot-scope="scope">
						<!--{{scope.row.mg_state}}-->
						<!--修改按钮-->
						<el-button @click="editDialog(scope.row.id)" icon="el-icon-edit" size="mini" type="primary" />
						<!--删除按钮-->
						<el-button @click="removeUser(scope.row.id)" icon="el-icon-delete" size="mini" type="danger" />
						<!--分配角色按钮-->
						<el-button @click="allotRole(scope.row)" icon="el-icon-setting" size="mini" type="warning" />
					</template>
				</el-table-column>
			</el-table>
			<!--分页区域-->
			<el-pagination
				:current-page="queryInfo.pagenum"
				:page-size="queryInfo.pagesize"
				:page-sizes="[5, 10, 15, 20]"
				:total="total"
				layout="total, sizes, prev, pager, next, jumper"
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
			/>
		</el-card>
		<!--添加用户的 Dialog 对话框-->
		<el-dialog :visible.sync="dialogVisible" title="添加用户" width="50%" @close="addDialogClosed">
			<!--内容主体区域-->
			<el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px" status-icon>
				<!--用户名-->
				<el-form-item label="用户名" prop="username">
					<el-input v-model="addForm.username"></el-input>
				</el-form-item>
				<!--密码-->
				<el-form-item label="密码" prop="password">
					<el-input v-model="addForm.password"></el-input>
				</el-form-item>

				<el-form-item label="邮箱" prop="email">
					<el-input v-model="addForm.email"></el-input>
				</el-form-item>

				<el-form-item label="手机" prop="mobile">
					<el-input v-model="addForm.mobile"></el-input>
				</el-form-item>
			</el-form>

			<!--底部按钮区域-->
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="addUser">确 定</el-button>
			</span>
		</el-dialog>

		<!--修改用户对话框-->
		<el-dialog title="修改用户信息" :visible.sync="editVisible" width="30%" @close="editDialogClosed">
			<!--内容主体区域-->
			<el-form :model="editData" :rules="addFormRules" ref="editDataRef" label-width="70px" status-icon>
				<!--用户名-->
				<el-form-item label="用户名">
					<el-input v-model="editData.username" disabled></el-input>
				</el-form-item>

				<el-form-item label="邮箱" prop="email">
					<el-input v-model="editData.email"></el-input>
				</el-form-item>

				<el-form-item label="手机" prop="mobile">
					<el-input v-model="editData.mobile"></el-input>
				</el-form-item>
			</el-form>

			<span slot="footer" class="dialog-footer">
				<el-button @click="editVisible = false">取 消</el-button>
				<el-button type="primary" @click="submitEdit">确 定</el-button>
			</span>
		</el-dialog>

		<!--分配角色对话框-->
		<el-dialog title="提示" :visible.sync="allotRolesdialogVisible" @close="initData">
			<div>
				<p>当前用户：{{ userinfo.username }}</p>
				<p>当前角色：{{ userinfo.role_name }}</p>
				<p>
					分配角色：
					<el-select v-model="selectRolesId" placeholder="请选择">
						<el-option v-for="item in rightList" :key="item.id" :label="item.roleName" :value="item.id"> </el-option>
					</el-select>
				</p>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="allotRolesdialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="sublimtRoles">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
/* eslint-disable no-unused-vars,vue/no-dupe-keys */
export default {
	data() {
		// TODO 验证邮箱的校验规则
		// eslint-disable-next-line no-unused-vars
		let checkEamil = (rule, value, cb) => {
			// eslint-disable-next-line
			const regEamil = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
			if (regEamil.test(value)) {
				return cb()
			} else {
				cb(new Error('请输入正确邮箱地址'))
			}
		}
		// TODO 验证手机号码的校验规则
		// eslint-disable-next-line no-unused-vars
		let checkMobile = (rule, value, cb) => {
			// eslint-disable-next-line no-unused-vars
			const regMobile = /^(13[0-9]|14[01456879]|15[0-3,5-9]|16[2567]|17[0-8]|18[0-9]|19[0-3,5-9])\d{8}$/
			if (regMobile.test(value)) {
				return cb()
			} else {
				cb(new Error('请输入正确手机号码'))
			}
		}
		return {
			// TODO UserList,ajax请求传参
			queryInfo: {
				query: '',
				// TODO 当前页数(默认请求就是从第一页开始)
				pagenum: 1,
				// TODO 当前每页显示多少条数据
				pagesize: 5,
			},
			//TODO userlist 数据
			userList: [],
			// 总数量
			total: 0,
			dialogVisible: false,
			editVisible: false,
			allotRolesdialogVisible: false,
			rightList: [],
			selectRolesId: '',
			// TODO 添加用户表单数据
			addForm: {
				username: '',
				password: '',
				email: '',
				mobile: '',
			},
			// TODO 查询到的用户信息
			editData: {},
			// TODO 添加用户表单验证规则
			userinfo: {},
			addFormRules: {
				username: [
					{ required: true, message: '请输入用户名', trigger: 'blur' },
					{
						min: 5,
						max: 18,
						message: '长度在 5 到 18 个字符',
						trigger: 'blur',
					},
				],
				password: [
					{ required: true, message: '请输入密码', trigger: 'blur' },
					{
						min: 3,
						max: 10,
						message: '长度在 3 到 10 个字符',
						trigger: 'blur',
					},
				],
				email: [
					{ required: true, message: '请输入邮箱', trigger: 'blur' },
					{ validator: checkEamil, trigger: 'blur' },
				],
				mobile: [
					{ required: true, message: '请输入手机', trigger: 'blur' },
					{ validator: checkMobile, trigger: 'blur' },
				],
			},
		}
	},
	//   TODO 声明周期函数：页面绘制前执行
	created() {
		this.getUserList()
	},
	methods: {
		getUserList: async function () {
			const { data: res } = await this.$http.get('users', {
				params: this.queryInfo,
			})
			if (res.meta.status !== 200) return this.$message.error('获取用户列表失败')
			this.userList = res.data.users
			this.total = res.data.total
		},
		// TODO 监听选择 每页显示多少条数据
		handleSizeChange(newSize) {
			this.queryInfo.pagesize = newSize
			this.getUserList()
		},

		// TODO 监听选择第几页
		handleCurrentChange(newPage) {
			this.queryInfo.pagenum = newPage
			this.getUserList()
		},
		// TODO 监听switch开关的状态 put请求
		async useStatuChange(switchState) {
			const { data: res } = await this.$http.put(`users/${switchState.id}/state/${switchState.mg_state}`)
			if (res.meta.status !== 200) {
				switchState.mg_state = !switchState.mg_state
				return this.$message.error('用户状态设置失败')
			} else {
				this.$message.success('用户状态设置成功')
			}
		},
		// TODO 监听添加用户对话框关闭事件
		addDialogClosed() {
			this.$refs.addFormRef.resetFields()
		},

		// TODO 点击确定按钮，添加新用户操作
		addUser() {
			// TODO 验证表单内容
			this.$refs.addFormRef.validate(async valid => {
				if (!valid) return
				//如果通过，发起ajax请求
				// eslint-disable-next-line no-unused-vars
				const { data: res } = await this.$http.post('users', this.addForm)
				if (res.meta.status !== 201) return this.$message.error('添加失败')
				this.$message.success('添加成功')
				// 隐藏添加对话框
				this.dialogVisible = false
				// 重新渲染用户列表
				await this.getUserList()
			})
		},

		// TODO 点击编辑,展示修改对话框，获取当前用户信息
		async editDialog(id) {
			this.editVisible = true
			const { data: res } = await this.$http.get('users/' + id)
			if (res.meta.status !== 200) return this.$message.error('获取失败')
			// this.$message.success("获取成功");
			this.editData = res.data
			// console.log(res.data);
		},

		//TODO 监听添加用户对话框关闭事件,重置未保存数据
		editDialogClosed() {
			this.$refs.editDataRef.resetFields()
		},

		// TODO 编辑用户提交
		submitEdit() {
			this.$refs.editDataRef.validate(async valid => {
				if (!valid) return
				const { data: res } = await this.$http.put('users/' + this.editData.id, {
					email: this.editData.email,
					mobile: this.editData.mobile,
				})
				if (res.meta.status !== 200) return this.$message.error('修改失败')
				this.editVisible = false
				await this.getUserList()
				this.$message.success('修改成功')
			})
		},

		// 删除用户操作
		removeUser(id) {
			this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(async () => {
					const { data: res } = await this.$http.delete('users/' + id)
					if (res.meta.status !== 200) {
						return this.$message.error('删除失败')
					}
					await this.getUserList()
					this.$message({
						type: 'success',
						message: '删除成功!',
					})
				})
				.catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除',
					})
				})
		},

		// 获取角色列表操作
		async allotRole(userinfo) {
			this.userinfo = userinfo
			this.allotRolesdialogVisible = true
			const { data: res } = await this.$http.get('roles')
			if (res.meta.status !== 200) {
				return this.$message.error('获取角色失败')
			}
			this.rightList = res.data
		},

		//提交已选中的角色操作
		async sublimtRoles() {
			console.log(this.userinfo.id)
			const { data: res } = await this.$http.put(`users/${this.userinfo.id}/role`, {
				rid: this.selectRolesId,
			})
			console.log(res)
			if (res.meta.status !== 200) {
				return this.$message.error('分配角色失败')
			}
			this.$message.success('分配角色成功')
			this.getUserList()
			this.allotRolesdialogVisible = false
		},

		// 分配角色对话框关闭时，清空数据
		initData() {
			this.selectRolesId = ''
			this.userinfo = {}
		},
	},
}
</script>

<style lang="less" scoped></style>
